package cn.wmingming.e3mall.order.service.impl;

import cn.wmingming.common.jedis.JedisClient;
import cn.wmingming.common.pojo.E3Result;
import cn.wmingming.e3mall.mapper.TbOrderItemMapper;
import cn.wmingming.e3mall.mapper.TbOrderMapper;
import cn.wmingming.e3mall.mapper.TbOrderShippingMapper;
import cn.wmingming.e3mall.order.pojo.OrderInfo;
import cn.wmingming.e3mall.order.service.OrderService;
import cn.wmingming.e3mall.pojo.TbOrder;
import cn.wmingming.e3mall.pojo.TbOrderItem;
import cn.wmingming.e3mall.pojo.TbOrderShipping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private JedisClient jedisClient;
    @Value("${ORDER_ID}")
    private String ORDER_ID;
    @Value("${ORDER_ID_START}")
    private String ORDER_ID_START;
    @Value("${ORDER_ITEM_ID}")
    private String ORDER_ITEM_ID;
    @Autowired
    private TbOrderMapper orderMapper;
    @Autowired
    private TbOrderItemMapper orderItemMapper;
    @Autowired
    private TbOrderShippingMapper orderShippingMapper;



    @Override
    public String genOrderId() {
        //利用redis的特性生成不会重复的orderId

        //1 redis中不存在orderId的key，设置并初始默认值
        if(!jedisClient.exists(ORDER_ID)){
            return jedisClient.set(ORDER_ID,ORDER_ID_START);
        }
        //2 redis中存在orderId的key，自增
        return jedisClient.incr(ORDER_ID).toString();
    }

    @Override
    public String genOrderItemId() {

        return jedisClient.incr(ORDER_ITEM_ID).toString();
    }

    @Override
    public E3Result insertOrderInfo(OrderInfo orderInfo) {
        //分别将数据插入对应的表中
        orderMapper.insert(orderInfo);
        for (TbOrderItem item:orderInfo.getOrderItems()){
            orderItemMapper.insert(item);
        }
        orderShippingMapper.insert(orderInfo.getOrderShipping());
        return E3Result.ok();
    }
}
